import axios from "axios";
import { REQUEST_TIMEOUT, FILE_REQUEST } from "@/config";
import { ElMessage } from "element-plus";
import router from "@/router";
import { useUserStore } from "@/store";

let source = axios.CancelToken.source();

export const instance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API || "/api",
  timeout: REQUEST_TIMEOUT,
});

instance.interceptors.request.use((config) => {
  const useStore = useUserStore();
  config.headers["Authorization"] = useStore.token;
  config.headers.token = useStore.token;
  return config;
});

// token失效&异常处理，需后端确定报文结构再做处理
instance.interceptors.response.use((response) => {
  // 如果请求是文件类请求直接返回，因为返回的数据data没有结构
  if (
    FILE_REQUEST.some((item) => response.request.responseURL.includes(item))
  ) {
    return response.data;
  }
  if (
    response.data.code !== 0 &&
    response.data.code !== 200 &&
    response.data.code !== 401
  ) {
    ElMessage({
      type: "error",
      message: response.data.msg || "系统异常",
    });
  } else if (response.data.code === 401) {
    // 当token失效的时候取消所有的请求
    source.cancel();
    source = axios.CancelToken.source();
    router.replace("/login");
    ElMessage({
      type: "error",
      message: "登录超时，请重新登录",
    });
  }
  return response.data;
});

export const getRequest = (url, params) => {
  return instance({
    url,
    method: "get",
    params: {
      ...params,
    },
    cancelToken: source.token,
  });
};

export const postRequest = (url, data) => {
  return instance({
    url,
    method: "post",
    data,
    cancelToken: source.token,
  });
};

export const downloadRequest = (url, params) => {
  return instance({
    url,
    method: "get",
    responseType: "blob",
    params: {
      ...params,
    },
    cancelToken: source.token,
  });
};
